package com.zlw.framework.web.server;

import com.zlw.framework.web.servlet.DispatcherServlet;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;

/**
 * @ClassName TomcatServer
 * @Description TODO
 * @Author zhaoluowei
 * @Date 2020/1/28  16:57
 * @Version 1.0
 */

public class TomcatServer {

    private Tomcat tomcat;
    private String[] args;

    public TomcatServer(String[] args) {
        this.args = args;
    }

    public void startServer() throws LifecycleException {
        tomcat = new Tomcat();
        tomcat.setPort(6699);
        tomcat.start();

        Context context = new StandardContext();
        //设置 路径
        context.setPath("");
        //设置 生命周期监听器
        context.addLifecycleListener(new Tomcat.FixContextListener());

        DispatcherServlet testServlet = new DispatcherServlet();
        Tomcat.addServlet(context, "dispatcherServlet", testServlet)
                .setAsyncSupported(true);
        //添加 servlet 到 uri的 映射。
        context.addServletMappingDecoded("/", "dispatcherServlet");
        tomcat.getHost().addChild(context);



        Thread awaitThread = new Thread("tomcat_await_thread") {
            @Override
            public void run() {
                //super.run();
                TomcatServer.this.tomcat.getServer().await();
            }
        };

        awaitThread.setDaemon(false);
        awaitThread.start();
    }


}
